<?php

namespace app\controllers\admin\uni\order;

use app\controllers\admin\AdminController;
use app\models\order\Order;
use app\models\order\OrderItem;
use app\models\order\OrderLogistics;

class BaseController extends AdminController
{
    public function actionSaveExpress()
    {
        $company_id = $this->post('company_id');
        $express_sn = $this->post('express_sn');

        $order_id = $this->post('order_id');
        $order_item_id = $this->post('order_item_id');
        $user_address_id = $this->post('user_address_id');

        // var_dump($company_id, $express_sn, $order_id, $order_item_id, $user_address_id);
        //
        // var_dump(222222);exit;
        //
        // OrderLogistics::deleteAll(['order_id' => $order_id, 'order_item_id' => $order_item_id]);

        $model = new OrderLogistics();
        $model->order_id = $order_id;
        $model->order_item_id = $order_item_id;
        $model->user_address_id = $user_address_id;
        $model->express_company_id = $company_id;
        $model->express_sn = $express_sn;
        $model->status = 1;

        if ($model->save()) {

            // result
            $logistics = OrderLogistics::find()
                ->where(['id' => $model->id])
                ->with(['company', 'address'])
                ->asArray()
                ->one();

            // order status
            $order = Order::findOne(['id' => $order_id]);
            $item_count = OrderItem::find()
                ->where(['order_id' => $order_id])
                ->andWhere(['is_express' => 1])
                ->count();
            $logistics_count = OrderLogistics::find()
                ->where(['order_id' => $order_id])
                ->count();
            if ($logistics_count >= $item_count) {
                $order->status = Order::$statusMapping['WAIT_RECEIVING'];
                $order->save();
            }

            return $this->success([
                'logistics' => $logistics,
                'order_status' => $order->status,
            ]);
        }

        return $this->fail();
    }
}